package casa.depesos.app.com.dlg;

import static android.app.Activity.RESULT_OK;

import android.content.Intent;
import android.os.Bundle;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.recyclerview.widget.LinearLayoutManager;

import casa.depesos.app.com.activity.BankActivity;
import casa.depesos.app.com.adapter.BankCardDlgAdapter;
import casa.depesos.app.com.databinding.DlgCardListBinding;
import casa.depesos.app.com.http.ReqCallback;
import casa.depesos.app.com.http.bean.BankCardBean;
import casa.depesos.app.com.http.data.BankCard;
import casa.depesos.app.com.http.req.BankCardReq;

public class CardDlg extends FullScreenDlg {

    DlgCardListBinding binding;
    BankCardDlgAdapter adapter;
    boolean add = false;

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        binding = DlgCardListBinding.inflate(inflater, container, false);
        binding.list.setLayoutManager(new LinearLayoutManager(getActivity()));
        adapter = new BankCardDlgAdapter(this, null);
        binding.list.setAdapter(adapter);

        binding.add.setOnClickListener(new View.OnClickListener() {
            @Override
            public void onClick(View v) {
                Intent i = new Intent(getActivity(), BankActivity.class);
                i.putExtra("from", 1);
                startActivityForResult(i, 1);
            }
        });
        return binding.getRoot();
    }

    @Override
    public void onActivityResult(int requestCode, int resultCode, @Nullable Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 1 && resultCode == RESULT_OK) {
            add = true;
        }
    }

    @Override
    public void onResume() {
        super.onResume();
        getData();
    }

    private void getData() {
        showLoading();
        new BankCardReq().req(new ReqCallback<BankCardBean>() {
            @Override
            public void callback(boolean success, BankCardBean bean) {
                hideLoading();
                if (success && bean.isValid()) {
                    adapter.setData(bean.card);
                }
            }
        });
    }

    @Override
    public void dismiss() {
        isOk = add;
        value = null;
        super.dismiss();
    }

    public void selectCard(BankCard card) {
        isOk = true;
        value = card;
        super.dismiss();
    }
}
